/**
 * verify code 生成
 */
var code; // 在全局 定义验证码
function createCode() {
	code = "";
	var codeLength = 4;// 验证码的长度
	//var checkCode = $("#"+id);
	//checkCode.val("");
	var selectChar = new Array(2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E',
			'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T',
			'U', 'V', 'W', 'X', 'Y', 'Z');

	for (var i = 0; i < codeLength; i++) {
		var charIndex = Math.floor(Math.random() * 32);
		code += selectChar[charIndex];
	}
	if (code.length != codeLength) {
		createCode();
	}
	$("#imgcode").html(code);
	return code;
}

$(function(){
	code = createCode();
});

//去除前后空格的方法
String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, '');
};

//按下回车键时的响应
document.onkeydown=function(event){
    var e = event || window.event || arguments.callee.caller.arguments[0];     
     if(e && e.keyCode==13){ // enter 键
         $("#login_btn").click();
    }
}; 
$('#login_btn').on('click', function() {
	var msg = $("#msg");
	loginname = $("#loginname");
	loginpassword = $("#loginpassword");
	codeword = $("#verifycode");
	if(loginname.val().trim()==""){
		msg.html("用户名不可为空");
		msg.css("display","block");
		return false;
	}
	if(loginpassword.val().trim()==""){
		msg.html("密码不可为空");
		msg.css("display","block");
		return;
	}
	if(codeword.val().trim()==""){
		msg.html("验证码不可为空");
		msg.css("display","block");
		return;
	} 
	if(codeword.val().trim().toLocaleUpperCase()!=code){
		msg.html("验证码错误");
		codeword.val("");
		msg.css("display","block");
		code = createCode('imgcode');
		return;
	}

	$.ajax({
        type: "post",
        url: contextPath + "/sysusr/login",
        data:{loginname:$('input[name="loginname"]').val(),loginpassword:hex_md5($('input[name="loginpassword"]').val()),ValidateCode:$('input[name=ValidateCode]').val()},
        dataType: "text",
        success: function (data) {
            if (data == "faliure") {
                $('#msg').html("用户名或密码错误！").css({color:"red"});
                return false;
            } else if(data == "false_ValidateCode"){
            	$('#msg').html("验证码错误!").css({color:"red"});
                return false;
            }else if(data == "success"){
                $('#msg').html("登录成功！").css({color:"green"});
            	setTimeout(function () {
            		 location.href = "sysusr/index.html";
            	}, 1000); //页面刷新
            	return false;
            }else if(data == "scenicSpot"){
				$('#msg').html("登录成功！").css({color:"green"});
				setTimeout(function () {
					location.href = "sysusr/scenicSpotIndex.html";
				}, 1000); //页面刷新
				return false;
			}
        },
        error: function (XMLHttpRequest, textStatus,errorThrown) {
            //alert(errorThrown);
            return false;
        }
    });
});